<template>
  <div class="container">
    <div class="container-content">
      <vab-query-form>
        <vab-query-form-top-panel>
          <el-form :inline="true" label-width="80px" :model="state.queryForm">
            <el-form-item label="区域名称">
              <el-input
                v-model="state.queryForm.areaName"
                placeholder="区域名称"
              />
            </el-form-item>
            <el-form-item label="区域编码">
              <el-input
                v-model="state.queryForm.areaCode"
                placeholder="区域编码"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <easy-dict-select
                v-model:default-value="state.queryForm.status"
                dict-code="1002"
                show-all="Y"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                icon="refresh-left"
                type="warning"
                @click="handleResetQuery"
              >
                重置
              </el-button>
              <el-button icon="search" type="primary" @click="handleSearch">
                查询
              </el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-top-panel>
        <vab-query-form-left-panel :span="24">
          <el-button icon="circle-plus" type="primary" @click="handleAdd">
            添加
          </el-button>
        </vab-query-form-left-panel>
      </vab-query-form>
      <el-table
        ref="tableRef"
        v-loading="areaTable.loading"
        border
        stripe
        :data="areaTable.dataList"
        :height="areaTable.height"
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle"
        row-key="id"
        lazy
        :load="loadChildren"
        :tree-props="{
          children: 'children',
          hasChildren: 'haschildren',
          checkStrictly: true
        }"
        @sort-change="handleSortChange"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column
          align="left"
          label="区域名称"
          prop="areaName"
          width="280"
        />
        <el-table-column
          align="left"
          label="区域编码"
          prop="areaCode"
          width="120"
        />
        <el-table-column
          align="left"
          label="区域简称"
          prop="shortName"
          width="120"
        />
        <el-table-column
          align="center"
          label="状态"
          prop="statusDesc"
          width="100"
        />
        <el-table-column align="center" label="级别" prop="level" width="100" />
        <el-table-column
          align="center"
          label="排序号"
          prop="sort"
          width="100"
        />
        <el-table-column
          align="center"
          :formatter="datetimeFormat"
          label="创建时间"
          prop="createTime"
          width="160"
        />
        <el-table-column
          align="center"
          :formatter="datetimeFormat"
          label="修改时间"
          prop="updateTime"
          width="160"
        />
        <el-table-column align="center" fixed="right" label="操作" width="140">
          <template #default="{ row }">
            <el-button size="small" type="warning" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <AreaEdit ref="editRef" width="50%" @confirm="handleConfirmEdit" />
    </div>
  </div>
</template>
<script setup lang="ts" name="Area">
import { useMessage, useMessageBox } from "@/hooks/message";
import { datetimeFormat, filterTreeNode } from "@/utils/common";
import {
  queryTreeTable,
  queryTree,
  deleteObjs
} from "@/api/admin/system/area/";
import { useTable } from "@/hooks/table";
import type { BasicTableProps } from "@/hooks/table";
import EasyDictSelect from "@/components/dictSelect.vue";
import AreaEdit from "./components/formEdit.vue";
import { nextTick, onMounted, reactive, ref } from "vue";

const tableRef = ref<any>(null);
const editRef = ref<any>(null);

const state = reactive({
  idMaps: new Map(),
  queryForm: {
    areaName: "",
    areaCode: "",
    status: "ALL"
  }
});

const tableOptions = reactive<BasicTableProps>({
  autoLoad: true,
  isPage: false,
  queryForm: {
    pid: "0"
  },
  queryFunction: queryTreeTable,
  ascs: ["sort"]
});

const {
  instance: areaTable,
  tableStyle,
  queryTableData,
  handleSelectionChange,
  handleResetQuery,
  handleRowClick,
  handleSortChange,
  handleToggleHeight
} = useTable(tableOptions, tableRef);

const handleSearch = async () => {
  if (
    state.queryForm.areaName ||
    state.queryForm.areaCode ||
    state.queryForm.status != "ALL"
  ) {
    queryTableData({
      pid: null,
      areaName: state.queryForm.areaName,
      areaCode: state.queryForm.areaCode,
      status: state.queryForm.status
    });
  } else {
    queryTableData({ pid: "0" });
  }
};

const queryApiData = async (pid, resolve) => {
  const params = {
    pid: "0"
  };
  if (pid) {
    params.pid = pid;
  }
  queryTree(params).then(res => {
    if (res.code === 200) {
      const list = res.data;
      resolve(list);
    } else {
      resolve();
    }
  });
};

const loadChildren = async (tree, treeNode, resolve) => {
  state.idMaps.set(tree.id, { tree, treeNode, resolve });
  queryApiData(tree.id, resolve);
};

onMounted(() => {
  handleToggleHeight(-50);
});

const handleAdd = () => {
  const row = {};
  editRef.value?.show(row);
};

const handleEdit = row => {
  if (row.id) {
    editRef.value?.show(row, false);
  } else {
    useMessage().error("未选中任何行");
  }
};

const handleDelete = row => {
  if (row && row.id) {
    useMessageBox()
      .confirm("删除的数据将无法恢复，是否继续")
      .then(async () => {
        deleteObjs(row.id).then(res => {
          if (res.code === 200) {
            useMessage().success("删除成功");
            queryTableData();
          } else {
            useMessage().success(res.msg);
          }
        });
      });
  }
};

const handleConfirmEdit = pid => {
  nextTick(async () => {
    const rtr = state.idMaps.get(pid);
    //如果父节点已经展开过
    if (rtr) {
      await loadChildren(rtr.tree, rtr.treeNode, rtr.resolve);
    } else {
      //如果父节点没有展开过
      const pNode = filterTreeNode(areaTable.dataList, pid, "id");
      //且父节点不属于根节点
      if (!pNode) {
        queryTree({
          pid: pid
        }).then(res => {
          if (res.code === 200) {
            const list = res.data;
            //如果当前修改节点是根节点
            if (pid === "0") {
              //将table的结果赋值为查询结果
              areaTable.dataList = list;
            } else {
              console.log(tableRef.value, pid, list);
              //否则修改父节点的懒加载结果
              tableRef.value.store.states.lazyTreeNodeMap.value[pid] = list;
            }
          }
        });
      } else {
        queryTableData({ pid: pid });
      }
    }
  });
};
</script>
